import {defaultMarkDownOptions, defaultOptions} from "@/common/const";

export var updataOptions = (options) => {
    let result = window.utools.db.put(options);
    options._rev = result.rev
    return options
}

export var mergeThemeOptions = (themes, options) => {
    if (themes.contentTheme) {
        options.preview.theme.current = themes.contentTheme;
    }
    if (themes.codeTheme) {
        options.preview.hljs.style = themes.codeTheme;
    }
    if (themes.contentTheme && themes.contentTheme == "dark") {
        options.theme = "dark"
    } else {
        options.theme = "classic"
    }
    return options;
}
export var upDataEditMode = (mode, options, vditor) => {
    // console.log(vditor.vditor)
    try {
        if (vditor != null && vditor.getCurrentMode() != mode) {
            options.mode = mode
            let value = vditor.getValue()
            vditor.setCurrentEditMode(vditor.vditor, mode, "")
            vditor.setValue(value)
            return updataOptions(options)
        }
    } catch (e) {
        return options
    }
    return options
}

export var upDataThemes = (themes, options, vditor) => {
    try {
        options = mergeThemeOptions(themes, options);
        vditor.setTheme(options.theme, options.preview.theme.current, options.preview.hljs.style);
    } catch (e) {
        return options
    }
    return updataOptions(options)
}

export var markDownOptions = () => {
    return window.utools.db.get("markdown_options");
}
export var getBaseOptions = () => {
    return window.utools.db.get("base_options");
}

export var initSetting = () => {
    //初始化默认配置
    var markdownOptions = window.utools.db.get("markdown_options");
    var baseOptions = window.utools.db.get("base_options");

    if (baseOptions){
        if (baseOptions.md_version == "1.0.0"){
            window.utools.db.remove("markdown_options")
            window.utools.db.remove("base_options")

            window.utools.db.put(defaultOptions)
            window.utools.db.put(defaultMarkDownOptions)
            window.newDir(window.HOME_DIR,()=>{})
            window.newDir(window.HOME_DIR+"/默认记事本/",()=>{})
            window.cpFile(window.getScriptPath()+"/help.md",window.HOME_DIR+"/使用必读.md")
        }
    }else {
        window.utools.db.put(defaultOptions)
        window.utools.db.put(defaultMarkDownOptions)
        window.newDir(window.HOME_DIR,()=>{})
        window.newDir(window.HOME_DIR+"/默认记事本/",()=>{})
        window.cpFile(window.getScriptPath()+"/help.md",window.HOME_DIR+"/使用必读.md")
    }

    baseOptions = window.utools.db.get("base_options");
    console.log(baseOptions)
    window.setDocHomeDir(baseOptions.doc_root_path)

    console.log("DB初始化完毕")
    return true
}


